# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.http import JsonResponse
from django.http import StreamingHttpResponse
from django.http import FileResponse
from http import HTTPStatus
import json
# 引入鉴权装饰器
from vue_app.utils.auth_permission import auth_permission_require
# 引入数据模型
from vue_app.models import DeviceMgrTable
# 引入序列化器
from django.core import serializers

# 引入模块服务
from vue_app.module.module_map import search_lnglat
from vue_app.module.machine_learning_model import api_debug
import os
from django.utils.encoding import escape_uri_path
from xlwt import Workbook

# 地图服务
@auth_permission_require('')
def mapservice(request):
    # response
    response = {}
    # data
    data = json.loads(request.body)
    # 参数
    addr = data.get("addr")
    # 调用模块
    lng, lat = search_lnglat(addr)
    # 返回
    response.update({"lat_lng": "{},{}".format(lng, lat)})
    response.update({"code": 20000})
    return JsonResponse(response)

def uploads(request):
    file = request.FILES.get("data")
    print(file)
    api_debug(file)
    # # 返回下载代码 - debug直接返回
    # try:
    #     # 设置响应头， 流式传输
    #     response = StreamingHttpResponse(file)
    #     response["Content-Type"] = "application/octet-stream"
    #     response["Content-Disposition"] = "attachment;filename={}".format("download_file")
    #     return response
    # except:
    #     return HttpResponse("Sorry but Not Found the File")

    response = {}
    response.update({"FileName": file.name})
    response.update({"TRJ": "ABC"})
    response.update({"code": 20000})
    return JsonResponse(response)

# @auth_permission_require('')
def downloads(request):
    # debug file
    def file_iterator(file_path, chunk_size=512):
        """
        文件生成器,防止文件过大，导致内存溢出
        :param file_path: 文件绝对路径
        :param chunk_size: 块大小
        :return: 生成器
        """
        with open(file_path, mode='rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    def file_byte_io(dataframe):
        from io import BytesIO
        import pandas as pd
        output = BytesIO()
        writer = pd.ExcelWriter(output)
        dataframe.to_excel(writer, "filename.xlsx", encoding="utf-8", index=None, engine="xlsxwriter")
        writer.save()
        output.seek(0)
        workbook = output.getvalue()
        return workbook


    def big_file_download(download_file_path, filename, dataframe):
        try:
            # 本地文件
            # response = StreamingHttpResponse(file_iterator(download_file_path))
            # ByteIO
            s = file_byte_io(dataframe)
            response = StreamingHttpResponse(file_byte_io(dataframe))
            # 增加headers
            response['Content-Type'] = 'application/octet-stream'
            response['Access-Control-Expose-Headers'] = "Content-Disposition, Content-Type"
            response['Content-Disposition'] = "attachment; filename={}".format(escape_uri_path(filename))
            return response
        except Exception:
            return JsonResponse({'status': HTTPStatus.BAD_REQUEST, 'msg': 'Excel下载失败'},
                                status=HTTPStatus.BAD_REQUEST)

    # print(request.data)
    file = request.FILES.get("data")
    print(file)
    dataframe = api_debug(file)

    # filename = request.data.get("filename.txt")
    filename = "filename.xlsx"
    download_file_path = os.path.join("./", filename)
    print("download_file_path", download_file_path)
    # 保存本地临时文件
    dataframe.to_excel(download_file_path, index=None)

    response = big_file_download(download_file_path, filename, dataframe)
    if response:
        return response

    return JsonResponse({'status': 'HttpResponse', 'msg': 'Excel下载失败', "code": 20000})